<template>
	<om-addpage style="padding-top: 35px;" :menuName="menuName" @formSubmit="formSubmit" :busCode="busCode">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		getUrl,
		confirmModal,
		ptFloat,
		minusF,
		errorModal,
		ignoreHtml
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		hasEditor,
		getEditor,
		getEditorTitle,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		changeConfigAttr,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';

	export default {
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		provide() {
			return {
				formPage: this
			}
		},
		data() {
			return buildFormData({
				menuName:'',
				initValue: {

				},
				selectUsers: [],
				instCacheKey: "hr-kq-overtime-inst-cache",
				costInstId: '',
				costInstName: "",
				fileId: "",
				fileKey:'43',
				oldInst: '',
			})
		},
		methods: {
			getInstLevel(id) {
				let _that = this
				_that.om.request(
					"tinstitution/getInstInfo",
					{
						instId:id
					}
				).then(res=>{
					_that.$refs.autoform.formdata.instLevelId =  res.value.instcatId
					_that.$refs.autoform.formdata.instLevelName =  res.value.instcatName
				})
			},
			verifyDate(){
				let _that = this
				if(_that.$refs.autoform.hasEditor('topinfo',"overTimeDay")){
					if(!_that.$refs.autoform.formdata.overTimeDay){
						let title = _that.$refs.autoform.getEditorTitle('topinfo',"overTimeDay")
						_that.om.toast('请先选择'+title)
						return false
					}else{
						return true
					}
				}
			},
			verifyNew(){
				let _that = this
				_that.om.request(
					"toverTime/verifyNew"
				).then(res=>{
					if(res.value){
						errorModal(_that,"提示信息",res.value,()=>{
							uni.navigateBack({
							})
						})
					}
				})
			},
			clearDate(){
				let _that = this
				_that.$refs.autoform.clear("topinfo","overTimeDay")
				_that.showBtn()
			},
			
			showBtn() {
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				_that.om.request(
					"dataDict/getIntByCode",
					{
						code: 'DD016169040'
					}
				).then(res=>{
					if(res.succeed){
						if(!res.value){
							// if (formdata.zposId) {
								_that.$refs.autoform.changeConfigAttr("overTimeInfo", "showButton", true)
								_that.$refs.autoform.changeConfigAttr("overTimeInfo", "buttonText", "加班模板")
								_that.$refs.autoform.changeConfigAttr("overTimeInfo", "buttonLink",
									"/pages/form/hr-kq-overtime/overtimeTemplate?zposId=" + formdata.zposId + '&date=' + formdata.overTimeDay +
									'&editId=' + _that.fileId + '&instId=' + formdata.instId+ '&instName=' + formdata.instName)
							// }
						}
					}
				})
			},
			onSelectZpos(item) {
				let _that = this
				if(_that.oldInst != item.instId){
					_that.oldInst = item.instId
					_that.$refs.autoform.formdata.instId = item.instId
					if(_that.subEditorObj["overTimeInfo"]){
						_that.subEditorObj["overTimeInfo"].workList = []
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr", JSON.stringify([]))
						_that.$set(_that.formdata, "objStr", JSON.stringify([]))
					}
					_that.showBtn()
					// _that.$refs.autoform.clearGroup("overTimeInfo")
					_that.getInstLevel(item.instId)
				}
			},
			onSelectDate(item) {
				let _that = this
				_that.showBtn()
				_that.om.request(
					"hrPosUtil/verifyFormDate", {
						date: item,
						busCode: _that.busCode
					},
					"post"
				).then(res => {
					if (res.value) {
						errorModal(_that, '提示信息', ignoreHtml(res.value), () => {
							_that.$refs.autoform.clear("topinfo", "overTimeDay")
						})
					}
				})
			},
			verifyObjStr() {
				let _that = this
				if(!_that.edit && !_that.checkedit){
					if (!_that.$refs.autoform.formdata.overTimeDay) {
						let editor2 = _that.$refs.autoform.getEditor("topinfo", "overTimeDay")
						_that.om.toast("请先选择" + editor2.title)
						return false
					} else {
						return true
					}
				}
			},
			onSelectInst(item) {
				let _that = this
				if(_that.oldInst != item.id){
					_that.oldInst = item.id
					_that.$refs.autoform.formdata.instId = item.id
					if(_that.subEditorObj["overTimeInfo"]){
						_that.subEditorObj["overTimeInfo"].workList = []
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr", JSON.stringify([]))
						_that.$set(_that.formdata, "objStr", JSON.stringify([]))
					}
					_that.showBtn()
					// _that.$refs.autoform.clearGroup("overTimeInfo")
					_that.getInstLevel(item.id)
				}
			},
			cleartInst(){
				let _that = this
				_that.oldInst = '';
				_that.$refs.autoform.clear("title1", "instId")
				// _that.$refs.autoform.formdata.instId = ''
				if(_that.subEditorObj["overTimeInfo"]){
					_that.subEditorObj["overTimeInfo"].workList = []
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr", JSON.stringify([]))
					_that.$set(_that.formdata, "objStr", JSON.stringify([]))
				}
				_that.showBtn()
				// _that.$refs.autoform.clearGroup("overTimeInfo")
				_that.$refs.autoform.clear("title1", "instLevelId")
			},
			formSubmit() {
				let _that = this
				let arr = []
				_that.formdata.updateBottomFileFlag= true
				delete _that.formdata.bottomFileUpload
				delete _that.formdata.bottomFileList
				if(Object.prototype.toString.call(_that.$refs.autoform.formdata.bottomFileList) == "[object String]"){
					_that.formdata.bottomFileListStr = _that.$refs.autoform.formdata.bottomFileList|| ''
				}else{
					_that.formdata.bottomFileListStr = JSON.stringify(_that.$refs.autoform.formdata.bottomFileList || []) || ''
					
				}
				for(let item of JSON.parse(_that.formdata.objStr)){
					if(item.isoutNoAttenceStr == true){
						item.isoutNoAttenceStr = "√"
						item.isoutNoAttence = true
						arr.push(item)
					}else{
						item.isoutNoAttence = null
						arr.push(item)
					}
				}
				_that.formdata.objStr = JSON.stringify(arr)
				if(_that.checkedit){
					this.om.formSave('commonForm/doCheckOrApproveUpdate', _that.formdata, _that)
				}else{
					this.om.formSave('toverTime/save', _that.formdata, _that)
				}
			},
			getWorkParam() {
				let _that = this
				return {
					zposId: _that.$refs.autoform.formdata.zposId,
					date: _that.$refs.autoform.formdata.overTimeDay,
					editId: this.fileId ? this.fileId : '',
					instId: _that.$refs.autoform.formdata.instId,
				}
			},
			initLoad(options) {
				let _that = this
				var ajaxArr = [{
					url: "wxPosBusiAuth/isnewList",
					param: {
						code: "HRS1204"
					},
					method: "post"
				},
				{
					url:"toverTime/getTitleInfo"
				},
				{
					url:"tinstitution/findInstList",
					param: {
						businessCode: "HRS1204",
						userId: _that.userId,
					},
				},{
					url:"wxPosBusiAuth/defaultTableMaker",
					param: {
						code: "HRS1204"
					},
					method: "post"
				}]
				let fileId = options.fileId
				if (fileId) {
					this.fileId = fileId
					ajaxArr.push({
						url: "toverTime/getInfo",
						param: {
							id: fileId
						}
					})
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					var defaultPosId = res[3].value.id || '';
					var defaultPosName = res[3].value.posName || '';
					var defaultInstId = res[3].value.instId || '';
					var defaultInstName = res[3].value.instName || '';
					//制表人
					changeEditor('topinfo', 'zuserId', {
						defaultName: _that.userName,
						defaultValue: _that.userId
					}, null, mainData)
					changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posName'), mainData)
					changeEditor('title1', 'instId', 'data', configSelectData(res[2], 'id', 'instName'), mainData)
					if (_that.subEditorObj["overTimeInfo"]) {
						let configData = _that.subConfigData["overTimeInfo"]
						let att = {
							getWorkParam: "getWorkParam"
						}
						if (hasEditor("overTimeInfo", "userId", configData)) {
							let title = getEditorTitle("overTimeInfo", "userId", configData)
							att.titleTemplate = "<%= userName || '未填写'%>"
						}
						if(hasEditor("overTimeInfo", "overTimeDate", configData)){
							let title = getEditorTitle("overTimeInfo", "overTimeDate", configData)
							att.subtitle1Template = title+":<%= overTimeDate || '未填写'%>" 
						}
						if(hasEditor("overTimeInfo", "startTime", configData)){
							let title = getEditorTitle("overTimeInfo", "startTime", configData)
							att.subtitle2Template = title+":<%= startTime || '未填写'%>" 
						}
						if(hasEditor("overTimeInfo", "endTime", configData)){
							let title = getEditorTitle("overTimeInfo", "endTime", configData)
							att.subtitle2Template += '-'+title+":<%= endTime || '未填写'%>" 
						}
						if(hasEditor("overTimeInfo", "workHoursCode", configData)){
							let title = getEditorTitle("overTimeInfo", "workHoursCode", configData)
							att.subtitle3Template = title+":<%= workHoursName || '未填写'%>" 
						}
						if(hasEditor("overTimeInfo", "salaryHandleId", configData)){
							let title = getEditorTitle("overTimeInfo", "salaryHandleId", configData)
							att.subtitle3Template += '/'+title+":<%= salaryHandleName || '未填写'%>" 
						}
						changeEditor("overTimeInfo", "objStr", att, mainData)
					}
					_that.$set(_that.formdata,"titleInfo",res[1].value)
					changeConfigAttr("overTimeInfo","subTitle",res[1].value,mainData)
					
					let tempFileList = []
					let fileUrlList = []
					changeEditor('bottominfo','bottomFileUpload','fileUploadKey',"43",mainData)
					changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
					changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
					
					if (fileId) {
						let fieldArr = getFormFields(mainData)
						fieldArr.push("id")
						for (let index in res[4].value.toverTime) {
							if (fieldArr.includes(index)) {
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata, index, res[4].value.toverTime[index])
								_that.$set(_that.formdata, index, res[4].value.toverTime[index])
							}
						}
						if(_that.formdata.bottomFileList){
							let tempFileList = []
							let fileUrlList = _that.formdata.bottomFileList.map(t=>{
								tempFileList.push(t.fileSaveName)
								return t.fileSaveName
							})
							changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
							changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
						}
						changeEditor("topinfo","zposId","type","labelbox",mainData)
						let dataList = _that._.cloneDeep(res[4].value.toverTime_data)
						for (let item of dataList) {
							if (item.ratio === 0) {
								item.ratio = "0"
							}
							if(item.isoutNoAttenceStr =="√"){
								item.isoutNoAttenceStr = true
							}
						}
						if(_that.subEditorObj["overTimeInfo"]){
							_that.subEditorObj["overTimeInfo"].workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr", JSON.stringify(dataList))
							_that.$set(_that.formdata, "objStr", JSON.stringify(dataList))
							delete res[4].value.dataList
						}
					}else{
						_that.verifyNew()
					}
					if(_that.checkedit){
						if(_that.subEditorObj["overTimeInfo"].workList.length == 1){
							let editor = _that.subEditorObj["overTimeInfo"]
							_that.$refs.autoform.openSubData(0,editor)
						}
					}
					_that.$nextTick(function() {
						if(!_that.$refs.autoform.formdata.zposId){
							_that.$refs.autoform.formdata.zposId = defaultPosId
							_that.$refs.autoform.formdata.zposName = defaultPosName
							_that.$refs.autoform.formdata.zinstId = defaultInstId
							_that.$refs.autoform.formdata.zinstName = defaultInstName
							
							_that.oldInst = defaultInstId
							_that.$refs.autoform.formdata.instId = defaultInstId
							_that.$refs.autoform.formdata.instName = defaultInstName
							_that.$nextTick(function() {
								_that.$refs.autoform.initSelectIndex('topinfo',"zposId")
								_that.$refs.autoform.initSelectIndex("title1","instId")
								_that.getInstLevel(defaultInstId)
							})
						}else{
							_that.$refs.autoform.initSelectIndex('topinfo',"zposId")
							for(let i=0; i<res[0].length; i++){
								if(res[0][i].id == _that.$refs.autoform.formdata.zposId){
									_that.oldInst = res[0][i].instId
									_that.$refs.autoform.formdata.instId = res[0][i].instId
									_that.$refs.autoform.formdata.instName = res[0][i].instName
									_that.$refs.autoform.initSelectIndex("title1","instId")
									_that.getInstLevel(res[0][i].instId)
								}
							}
						}
						_that.showBtn()
					})
				}, options)
			},
		},
		onUnload() {
			//#ifdef APP-PLUS
			let _that = this;
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
			//#endif
		},
		onShow() {
			let _that = this;
			if (_that.$refs.autoform) {
				for (let fileId in _that.subEditorObj) {
					let editor = _that.subEditorObj[fileId]
					uni.getStorage({
						key: getWorkCacheKey(fileId),
						success: (res) => {
							editor.workList = res.data
							for(let item of res.data){
								if(item.ratio == 0){
									item.ratio = "0"
								}
								if(item.overTimeDate !=  _that.$refs.autoform.formdata.overTimeDay){
									_that.$refs.autoform.clear("topinfo","overTimeDay")
								}
							}
							uni.removeStorage({
								key: getWorkCacheKey(fileId)
							})
						}
					})
				}
				uni.getStorage({
					key: "overtimeTemplateData",
					success: (res) => {
						if (res.data) {
							let d = res.data
							_that.subEditorObj["overTimeInfo"].workList= res.data
							uni.removeStorage({
								key: "overtimeTemplateData"
							})
						}
					}
				})
			}
		},
		onLoad(options) {
			let _that = this;
			_that.menuName = options.title || '加班审批';
			uni.setNavigationBarTitle({
				title: _that.menuName
			});
			this.initLoad(options)
		},
	}
</script>

<style>
</style>
